﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace IPCByMessages
{
    /// <summary>
    /// Creator of MessagesChannels
    /// </summary>
    public static class MessagesChannelManager
    {
        /// <summary>
        /// Establish asynchronous messages connection with remote host at specified port
        /// </summary>
        /// <param name="host">Remote host name or IP-address</param>
        /// <param name="port">Port to connect</param>
        /// <returns>Connected MessagesChannel</returns>
        public static IMessagesChannel EstablishAsyncConnection(string host, int port)
        {
            try
            {
                return new AsyncClientMesagesChannel(host, port);
            }
            catch(SocketException)
            {
                try
                {
                    return new AsyncServerMesagesChannel(port);
                }
                catch (SocketException ex1)
                {
                    throw new InvalidOperationException("Cannot create neither" +
                            "MessagesChannelManager nor ServerMesagesChannel",
                        ex1);
                }
            }
        }

        /// <summary>
        /// Establish synchronous messages connection with remote host at specified port
        /// </summary>
        /// <param name="host">Remote host name or IP-address</param>
        /// <param name="port">Port to connect</param>
        /// <returns>Connected MessagesChannel</returns>
        public static IMessagesChannel EstablishSyncConnection(string host, int port)
        {
            try
            {
                return new SyncClientMesagesChannel(host, port);
            }
            catch (SocketException)
            {
                try
                {
                    return new SyncServerMesagesChannel(port);
                }
                catch (SocketException ex1)
                {
                    throw new InvalidOperationException("Cannot create neither" +
                            "MessagesChannelManager nor ServerMesagesChannel",
                        ex1);
                }
            }
        }
    }
}
